$(function () {
    /**
     * 新增功能
     */
    $('.rewardsCategoryAdd').on('click', function () {
        var addtr = '<tr>'
            + '<td></td>'
            + '<td class="hidden"></td>'
            + '<td>'
            + '  <select class="input-sm form-control type">'
            + '     <option value="">请选择</option>'
            + '     <option value="0">奖</option>'
            + '     <option value="1">罚</option>'
            + '   </select>'
            + '</td>'
            + '<td>'
            + '     <input type="text" class="input-sm form-control rewardType">'
            + '</td>'
            + '<td>'
            + '  <a href="javascript:;" class="btn btn-xs btn-use save"><i class="fa fa-copy"></i> 保存</a>'
            + '  <a href="javascript:;" class="btn btn-warning btn-xs cancel"><i class="fa fa-times"></i> 取消</a>'
            + '</td>'
            + '</tr>';
        if ($('#rewardsCategory tbody tr .form-control').length == 0) {
            $('#rewardsCategory').find('tbody').prepend(addtr);
        }

        //保存
        $('#rewardsCategory tbody').on('click', '.save', function (event) {
        	var type = $('#rewardsCategory').find('.type').val();
        	var rewardType = $('#rewardsCategory').find('.rewardType').val();
        	if(rewardType==""||rewardType==null){
        		 toastr.error("请填写类别！");
        		 return;
        	}
        	if(type==""||type==null){
	       		 toastr.error("请选择奖惩种类！");
	       		 return;
        	}
            $.ajax({
                url: ctx + '/bizRewardsCategory/addNewRecord',
                type: 'POST',
                data: {
                	type:type,
                	rewardType:rewardType
	             },
                dataType: 'json',
                success: function (data) {
                    if (data.status == "success"){
//                    	DataTable.init();
                    	loadHtml('/bizRewardsCategory/index')
                    }
                    else
                   	 toastr.error(data.msg);
                },
                error: function (response) {
               	 toastr.error("系统错误");
                }
            });

            //按钮切换
            $(this).removeClass('save btn-use').addClass('edit btn-info');
            $(this).html('<i class="fa fa-edit"></i> 编辑');
            $(this).next().removeClass('cancel btn-warning').addClass('delete btn-danger');
            $(this).next().html('<i class="fa fa-trash-o"></i> 删除');
        });

        //取消
        $('#rewardsCategory tbody').on('click', '.cancel', function () {
                $(this).parent().parent().remove();
        });
    });
    
 
    /**
     * 编辑功能
     */
    $('#rewardsCategory tbody').on('click', '.edit', function () {
        var tds = $(this).parent().siblings();

        //奖惩种类
        var type = tds.eq(2).text().trim();

        //类别
        var rewardsType = tds.eq(3).text();

        tds.eq(0).html('');
        tds.eq(1).html(tds.eq(1).text().trim());
        tds.eq(2).html(tds.eq(2).text().trim());
//        if (type == "0") {
//            tds.eq(2).html('奖');
//        } else if (type == "1") {
//            tds.eq(2).html('惩');
//        }
//        if (type == "奖") {
//            tds.eq(2).html('' +
//                '<select class="input-sm form-control">'
//                + '     <option value="0" selected>奖</option>'
//                + '     <option value="1">罚</option>'
//                + '</select>');
//        } else if (type == "罚") {
//            tds.eq(2).html('' +
//                '<select class="input-sm form-control">'
//                + '     <option value="0">奖</option>'
//                + '     <option value="1" selected>罚</option>'
//                + '</select>');
//        }
        tds.eq(3).html('<input type="text" name="rewardsType" value="' + tds.eq(3).text().trim() + '" class="input-sm form-control rewardsType">');


        //按钮切换
        $(this).removeClass('edit btn-info').addClass('save-bj btn-use');
        $(this).html('<i class="fa fa-copy"></i> 保存');
        $(this).next().removeClass('delete btn-danger').addClass('cancel btn-warning');
        $(this).next().html('<i class="fa fa-times"></i> 取消');

        //取消
        $('#rewardsCategory tbody').on('click', '.cancel', function () {
            tds.eq(0).html('<label><input type="checkbox"><span class="text"></span></label>');
            tds.eq(2).html(type);
            tds.eq(3).html(rewardsType);


            //按钮切换
            $(this).removeClass('cancel btn-warning').addClass('delete btn-danger');
            $(this).html('<i class="fa fa-trash-o"></i> 删除');
            $(this).prev().removeClass('save btn-use').addClass('edit btn-info');
            $(this).prev().html('<i class="fa fa-edit"></i> 编辑');
        });


        //编辑保存
        $('#rewardsCategory tbody').on('click', '.save-bj', function (event) {
        	var rewardId = $(this).parent().siblings().eq(1).text();
        	var rewardType = $(this).parent().siblings().eq(3).find(".rewardsType").val();
        	$.ajax({
        		url : ctx + '/bizRewardsCategory/updateRecord',
        		type : 'POST',
        		dataType: 'json',
        		data : {
        			"rewardId":rewardId,
        			"rewardType":rewardType
        		},
        		success : function(data){
        			if(data.status != "success"){
        				toastr.error(data.msg);
        			}else{
        				DataTable.init();
        			}
        		},
        		error : function(){
        			toastr.error("系统错误");
        		}
        	});
        	return false;
        })
    });

    /**
     * 删除功能
     */
    $('#rewardsCategory tbody').on('click', '.delete', function () {
    	var rewardId = $(this).parent().siblings().eq(1).text();
    	$.ajax({
    		url : ctx + '/bizRewardsCategory/updateRecord',
    		type : 'POST',
    		dataType: 'json',
    		data : {
    			"rewardId":rewardId,
    			"deleteMark":0
    		},
    		success : function(data){
    			if(data.status != "success"){
    				toastr.error("删除不成功，请重试！");
    			}else{
    				DataTable.init();
    			}
    		},
    		error : function(){
    			toastr.error("系统错误");
    		}
    	});
    	return false;
    });
});

//初始化数据
var DataTable = function(){
	return{
		init: function(){
			var Table = $('#rewardsCategory').dataTable({
				"bPaginate": true,  //是否显示分页
            	"iDisplayLength": 15,
            	"bLengthChange": false,//每页显示的记录数
            	"bFilter": false, //搜索栏
            	"bSort": true, //是否支持排序功能
            	"bInfo": true, //显示表格信息
            	"bAutoWidth": false,  //自适应宽度
            	"bStateSave": true, //保存状态到cookie *************** 很重要 ， 当搜索的时候页面一刷新会导致搜索的消失。使用这个属性就可避免了
            	//"sPaginationType": "", //分页，一共两种样式，full_numbers和two_button(默认)
            	"sAjaxSource" : ctx+'/bizRewardsCategory/load',
        		"fnServerData": retrieveData,//用于替换默认发到服务端的请求操作  
            	"bServerSide": true,
            	"bDestroy": true,
                "bRetrieve": false,
                "oLanguage" : {
        			"sLengthMenu" : "每页显示 _MENU_ 条记录",
        			"sZeroRecords" : "抱歉， 没有找到",
        			"sInfo" : "从 _START_ 到 _END_ / 共 _TOTAL_ 条数据",
        			"sInfoEmpty" : "找不到相关数据",
        			"sInfoFiltered" : "数据表中共为 _MAX_ 条记录)",
        			"sProcessing": "正在加载中...",
        			"sSearch": "搜索",
        			"oPaginate" : {
        				"sFirst" : "首页",
        				"sPrevious" : "前一页",
        				"sNext" : "后一页",
        				"sLast" : "尾页"
        			},
        		},
        		"aoColumns" : [
       			            {
       			                "mData": "rewardId", 'sClass': "text-center", "bSortable": false, "mRender": function (data, type, full) {
       			                return '<label  class="labletab" style="padding-top: 0px"> <input name="ajaxcheckbox" type="checkbox" class="checkchild"> <span class="text" ></span> </label>';
       			            }
       			            },
       			            {"mData": "rewardId", 'sClass': "hiddenCol"},
       			            {"mData": "type", 'sClass': "text-center","mRender":function(data, type, full ){
       			            	if(data==0){
       			            		return'<span class="text">奖励</span>';
       			            	}else{
       			            		return'<span class="text">惩罚</span>';
       			            	}
       			            }},
       			            {"mData": "rewardType", 'sClass': "text-center"},
       			            {
       			                "mData": "rewardId",
       			                'sClass': "text-center",
       			                "bSortable": false,
       			                "mRender": function (data, type, full ) {
               			                    var u = '<a href="#" class="btn btn-info btn-xs edit" data-toggle="modal" data-target=".bs-example-modal-lg"><i class="fa fa-edit"></i> 编辑</a>&nbsp;&nbsp';
               			                    var d = '<a href="#" class="btn btn-danger btn-xs delete"><i class="fa fa-trash-o"></i> 删除</a>';
               			                    return u + d;
       			                }
       			            }
       			        ],
       			        "aoColumnDefs": [{
       		   	            sDefaultContent: '',
       		   	            aTargets: ['_all']
       		   	        }],
			});
		}
	}
}();
DataTable.init();
function retrieveData( sSource, aoData, fnCallback, oSettings ) {
	aoData.push( { "name": "pageNum", "value": (Math.ceil( oSettings._iDisplayStart / oSettings._iDisplayLength )+1) });
    aoData.push( { "name": "pageSize", "value": oSettings._iDisplayLength });  
    var searchVal = $('#searchVal').val();
    if(searchVal && searchVal.length != 0){
    	aoData.push({ "name": "searchVal", "value": searchVal});
    }
    $.ajax( {  
        "url": sSource,  
        "data": aoData,  
        "cache": false,  
        "dataType": 'json', 
        "type": "POST", 
        "success" :function(response) {
        	fnCallback(response.returnObject);
        }  
    } );  
}
//回车搜索
function search(){
	if(event.keyCode==13){
		DataTable.init();
	}
}